import base64
import logging
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class TicketChecker:
    def __init__(self, db_manager):
        self.db_manager = db_manager
        
    def decrypt_ticket(self, encrypted_data, aes_key):
        #解密票据数据
        try:
            aes_key = aes_key.encode('utf-8').ljust(16, b'\x00')[:16]
            cipher = AES.new(aes_key, AES.MODE_ECB)
            decoded_data = base64.b64decode(encrypted_data)
            decrypted_data = unpad(cipher.decrypt(decoded_data), AES.block_size)
            return decrypted_data.decode('utf-8')
        except Exception as e:
            logger.error(f'票据解密失败: {str(e)}')
            return None
        
    def check(self, ticket_data, aes_key):
        #核验票据
        # 解密票据数据
        decrypted_data = self.decrypt_ticket(ticket_data, aes_key)
        if not decrypted_data:
            return '核验失败: 票据数据解密错误'
        
        # 提取票号信息 (格式: prefix_i_random_hex)
        parts = decrypted_data.split('_')
        if len(parts) < 2:
            return '核验失败: 票据格式无效'
        
        ticket_number = parts[0]
        
        # 查询数据库
        sql = "SELECT id, ticket_number, entry_state FROM tickets WHERE ticket_data = %s"
        result = self.db_manager.execute_query(sql, (ticket_data,))
        
        if not result:
            return '核验失败: 票号不存在'
        
        ticket = result[0]
        entry_state = ticket['entry_state']
        
        if entry_state == 2:
            # 黑名单票据
            return f'核验失败：票据{ticket["ticket_number"]}已被列入黑名单，禁止入场'
        elif entry_state == 1:
            # 已入场
            return f'欢迎回来，{ticket["ticket_number"]}，您的ID是{ticket["id"]}，重复入场'
        else:
            # 更新入场状态和时间
            update_sql = "UPDATE tickets SET entry_state = 1, entry_time = %s WHERE id = %s"
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            if self.db_manager.execute_update(update_sql, (current_time, ticket['id'])):
                return f'欢迎，{ticket["ticket_number"]}，您的ID是{ticket["id"]}，首次入场'
            else:
                return f'核验警告: {ticket["ticket_number"]}验证成功，但更新入场状态失败'